/*
 * JIFCinemaAjout

 */
package cinescope2014.boundaries;

import cinescope2014.utilities.Globale;
import java.sql.*;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author pascal
 */
public class JIFCinemaAjout extends javax.swing.JInternalFrame {

    private Connection icn;
    private DefaultTableModel idtm;
    private Map<String, Integer> imapVilles;
    private Map<String, Integer> imapArrondissements;

    /**
     * Creates new form JIFCinemaAjout
     */
    public JIFCinemaAjout() {
        initComponents();

        try {
            // --- Connexion
//            Class.forName("org.gjt.mm.mysql.Driver");
//            String lsDSN = "jdbc:mysql://127.0.0.1:3306/cinescope2014";
//            icn = DriverManager.getConnection(lsDSN, "root", "");

            icn = Globale.getConnexion();
            idtm = (DefaultTableModel) jTableSalles.getModel();

            imapVilles = new HashMap();

            imapArrondissements = new HashMap();

            String lsSQL;
            PreparedStatement lpst;
            ResultSet lrs;

            //lsSQL = "SELECT * FROM ville ORDER BY nom_ville";
            lsSQL = "{CALL ville_select_IDF()}";

            lpst = icn.prepareStatement(lsSQL);
            lrs = lpst.executeQuery();

            jComboBoxVilles.addItem("<--Choisissez-->");
            imapVilles.put("<--Choisissez-->", 0);

            while (lrs.next()) {
                jComboBoxVilles.addItem(lrs.getString("nom_ville"));
                imapVilles.put(lrs.getString("nom_ville"), lrs.getInt("id_ville"));
            }

            lrs.close();
            lpst.close();

            lsSQL = "SELECT * FROM arrondissement ORDER BY nom_arrondissement";
            lsSQL = "{CALL arrondissement_select_tries()}";
            lpst = icn.prepareStatement(lsSQL);
            lrs = lpst.executeQuery();

            jComboBoxArrondissements.addItem("<--Choisissez-->");
            imapArrondissements.put("<--Choisissez-->", 0);

            while (lrs.next()) {
                jComboBoxArrondissements.addItem(lrs.getString("nom_arrondissement"));
                imapArrondissements.put(lrs.getString("nom_arrondissement"), lrs.getInt("id_arrondissement"));
            }

            lrs.close();
            lpst.close();

            jLabelMessage.setText("Okay !!!");

        } catch (SQLException ex) {
            jLabelMessage.setText(ex.getMessage());
        }

        setTitle("Nouveau Cinéma");
        setVisible(true);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabelMessage = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jTextFieldCodeCinema = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jTextFieldNomCinema = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jTextFieldAdresseCinema = new javax.swing.JTextField();
        jCheckBoxAccesPersonnesHandicapees = new javax.swing.JCheckBox();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTableSalles = new javax.swing.JTable();
        jButtonValiderNouveauCinema = new javax.swing.JButton();
        jButtonNouvelleSalle = new javax.swing.JButton();
        jComboBoxVilles = new javax.swing.JComboBox();
        jComboBoxArrondissements = new javax.swing.JComboBox();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jButtonSupprimerSalle = new javax.swing.JButton();

        setClosable(true);
        setIconifiable(true);
        setMaximizable(true);
        setResizable(true);

        jLabel1.setText("Nouveau cinéma ...");

        jLabelMessage.setText("Message :");

        jLabel2.setText("Code cinéma");

        jTextFieldCodeCinema.setText("12A");

        jLabel3.setText("Nom");

        jTextFieldNomCinema.setText("MK2 Bibliothèque");

        jLabel4.setText("Adresse");

        jTextFieldAdresseCinema.setText("23, avenue de France - Paris XIII");

        jCheckBoxAccesPersonnesHandicapees.setText("Accès aux personnes handicapées");

        jTableSalles.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "ID cinéma", "Nom salle", "Description salle"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, true, true
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTableSalles.getTableHeader().setReorderingAllowed(false);
        jScrollPane1.setViewportView(jTableSalles);

        jButtonValiderNouveauCinema.setText("Valider nouveau cinéma ...");
        jButtonValiderNouveauCinema.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonValiderNouveauCinemaActionPerformed(evt);
            }
        });

        jButtonNouvelleSalle.setText("Nouvelle salle");
        jButtonNouvelleSalle.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonNouvelleSalleActionPerformed(evt);
            }
        });

        jComboBoxVilles.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBoxVillesActionPerformed(evt);
            }
        });

        jLabel5.setText("Ville");

        jLabel6.setText("Arrondissement");

        jButtonSupprimerSalle.setText("Supprimer salle");
        jButtonSupprimerSalle.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonSupprimerSalleActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(jLabel1)
                        .addComponent(jLabelMessage, javax.swing.GroupLayout.PREFERRED_SIZE, 665, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jButtonValiderNouveauCinema, javax.swing.GroupLayout.PREFERRED_SIZE, 452, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGroup(layout.createSequentialGroup()
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jLabel2)
                                .addComponent(jLabel3)
                                .addComponent(jLabel4)
                                .addComponent(jLabel5)
                                .addComponent(jLabel6))
                            .addGap(29, 29, 29)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jTextFieldAdresseCinema)
                                .addGroup(layout.createSequentialGroup()
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(jCheckBoxAccesPersonnesHandicapees)
                                        .addComponent(jTextFieldCodeCinema, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(jTextFieldNomCinema, javax.swing.GroupLayout.PREFERRED_SIZE, 263, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                            .addComponent(jComboBoxArrondissements, javax.swing.GroupLayout.Alignment.LEADING, 0, 261, Short.MAX_VALUE)
                                            .addComponent(jComboBoxVilles, javax.swing.GroupLayout.Alignment.LEADING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                                    .addGap(0, 0, Short.MAX_VALUE)))))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jButtonNouvelleSalle, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jButtonSupprimerSalle, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jTextFieldCodeCinema, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jTextFieldNomCinema, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(jTextFieldAdresseCinema, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jCheckBoxAccesPersonnesHandicapees)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jComboBoxVilles, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jComboBoxArrondissements, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel6))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 57, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButtonNouvelleSalle)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButtonSupprimerSalle)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jButtonValiderNouveauCinema)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabelMessage)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButtonNouvelleSalleActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonNouvelleSalleActionPerformed
        // 
        String[] tLigne = new String[3];
        tLigne[1] = "Salle 1";
        tLigne[2] = "Grande";
        idtm.addRow(tLigne);
    }//GEN-LAST:event_jButtonNouvelleSalleActionPerformed

    private void jButtonValiderNouveauCinemaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonValiderNouveauCinemaActionPerformed
        /*
         Code sur 1 chiffre mini et eventuellement 1 caractère (Expression reguliere)
         Nom >= 2 caractères (Expression reguliere)
         Adresse >= 2 caractères (Expression reguliere)
         Ville et arrondissement <> de index 0
         Au moins une salle
         */

        int liKO = 0;
        StringBuilder lsbMessage = new StringBuilder();
        String lsSQL;
        PreparedStatement lpst;
//        ResultSet lrs;
        int liNouvelleCle = 0;
        String lsMotif;

        String lsCode = jTextFieldCodeCinema.getText();
        String lsNom = jTextFieldNomCinema.getText();
        String lsAdresse = jTextFieldAdresseCinema.getText();

        //String lsVille = jComboBoxVilles.getSelectedItem().toString();
        int liIndexVille = jComboBoxVilles.getSelectedIndex();
        int liIndexArrondissement = jComboBoxArrondissements.getSelectedIndex();

        lsMotif = "[A-Z0-9]{2,4}";
        if (!lsCode.matches(lsMotif)) {
            liKO++;
            lsbMessage.append("Code KO-");
        }
        lsMotif = ".{2,}";
        if (!lsNom.matches(lsMotif)) {
            liKO++;
            lsbMessage.append("Nom KO-");
        }
        lsMotif = "[A-Za-z0-9 ,-]{2,}";
        if (!lsAdresse.matches(lsMotif)) {
            liKO++;
            lsbMessage.append("Adresse KO-");
        }

        if (liIndexVille == 0 || liIndexArrondissement == 0) {
            //jLabelMessage.setText("Vous devez choisir une ville et/ou un arrondissement !!!");
            liKO++;
            lsbMessage.append("Vous devez choisir une ville et/ou un arrondissement !!!-");
        }
        if (jTableSalles.getRowCount() == 0) {
            liKO++;
            lsbMessage.append("Au moins une salle !!!-");
        }

        if (liKO == 0) {
            try {
                // PREPARATION
                // CREATE PROCEDURE cinescope2014.`cinemaInsert`(paramID_CINEMA INT(10),paramID_VILLE INT(10),paramID_ARRONDISSEMENT INT(10),paramCODE_CINEMA VARCHAR(10),paramNOM_CINEMA VARCHAR(50),paramADRESSE_CINEMA VARCHAR(100),paramTELEPHONE_CINEMA VARCHAR(50),paramTARIFS_CINEMA VARCHAR(100),paramDIVERS_CINEMA VARCHAR(100),paramRESEAU_CINEMA VARCHAR(50),paramACCES_HANDICAPES INT(10))
                lsSQL = "CALL cinemaInsert(?,?,?,?,?,?,?,?,?,?,?)";
//            lpst = icn.prepareStatement(lsSQL, Statement.RETURN_GENERATED_KEYS);
                lpst = icn.prepareStatement(lsSQL);

                // VALORISATION DES PARAMETRES
//            int id;
                lpst.setInt(1, Types.NULL);
                lpst.setInt(2, imapVilles.get(jComboBoxVilles.getSelectedItem().toString()));
                lpst.setInt(3, imapArrondissements.get(jComboBoxArrondissements.getSelectedItem().toString()));
                lpst.setString(4, jTextFieldCodeCinema.getText());
                lpst.setString(5, jTextFieldNomCinema.getText());
                lpst.setString(6, jTextFieldAdresseCinema.getText());
                lpst.setString(7, "");
                lpst.setString(8, "");
                lpst.setString(9, "");
                lpst.setString(10, "");

                int liAccesPersonneHandicapee;
                if (jCheckBoxAccesPersonnesHandicapees.isEnabled()) {
                    liAccesPersonneHandicapee = 1;
                } else {
                    liAccesPersonneHandicapee = 0;
                }
                lpst.setInt(11, liAccesPersonneHandicapee);

                // INSERTION
                lpst.executeUpdate();
                lpst.close();

                /*
                 RECUPERATION DU NOUVEL ID
                 SOIT AVEC PS SOIT AVEC FS
                 */
//            lsSQL = "{CALL newID()}";
//            lpst = icn.prepareStatement(lsSQL);
//            lrs = lpst.executeQuery();
//            lrs.next();
//            liNouvelleCle = lrs.getInt(1);
//            lrs.close();
                // 
                CallableStatement lcst;
                lsSQL = "{? = CALL get_new_ID()}";
                // COMPILATION DE LA FONCTION STOCKEE
                lcst = icn.prepareCall(lsSQL);
                lcst.registerOutParameter(1, Types.INTEGER);

                // EXECUTION FONCTION STOCKEE
                lcst.execute();

                // RECUPERATION DE LA VALEUR 
                liNouvelleCle = lcst.getInt(1);

                lcst.close();

//            lrs = lpst.getGeneratedKeys();
//            if (lrs.next()) {
//                liNouvelleCle = lrs.getInt(1);
//            } else {
//                liNouvelleCle = 111;
//            }
//            lrs.close();
                // `salleInsert`(paramID_SALLE INT(10),paramID_CINEMA INT(10),paramID_FESTIVAL INT(10),paramNOM_SALLE VARCHAR(50),paramDESCRIPTION_SALLE VARCHAR(100))
                lsSQL = "{CALL salleInsert(?,?,?,?,?)}";
                lpst = icn.prepareStatement(lsSQL);
                for (int i = 0; i < jTableSalles.getRowCount(); i++) {
                    jTableSalles.setValueAt(liNouvelleCle, i, 0);

                    lpst.setInt(1, Types.NULL);
                    lpst.setInt(2, liNouvelleCle);
                    lpst.setInt(3, Types.NULL);
                    lpst.setString(4, jTableSalles.getValueAt(i, 1).toString());
                    lpst.setString(5, jTableSalles.getValueAt(i, 2).toString());

                    lpst.executeUpdate();
                }

                lpst.close();

                icn.commit();

                jLabelMessage.setText("OKAY !!!");

                // NETTOYAGE ECRAN
                jTextFieldCodeCinema.setText("");
                jTextFieldNomCinema.setText("");
                jTextFieldAdresseCinema.setText("");
                for (int i = idtm.getRowCount() - 1; i >= 0; i--) {
                    idtm.removeRow(i);
                }
            } catch (SQLException e) {
                try {
                    icn.rollback();
                } catch (SQLException ex) {
                    Logger.getLogger(JIFCinemaAjout.class.getName()).log(Level.SEVERE, null, ex);
                }
                jLabelMessage.setText(e.getMessage());
            }
        } else {
            lsbMessage.deleteCharAt(lsbMessage.length() - 1);
            jLabelMessage.setText(lsbMessage.toString());
        }
    }//GEN-LAST:event_jButtonValiderNouveauCinemaActionPerformed

    private void jButtonSupprimerSalleActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonSupprimerSalleActionPerformed
        // 
        int liLigneSelectionnee = jTableSalles.getSelectedRow();

        if (liLigneSelectionnee == -1) {
            jLabelMessage.setText("Sélectionnez une ligne !!!");
        } else {
            idtm.removeRow(liLigneSelectionnee);
        }
    }//GEN-LAST:event_jButtonSupprimerSalleActionPerformed

    private void jComboBoxVillesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBoxVillesActionPerformed
        // 
        if (jComboBoxVilles.getSelectedItem().toString().equalsIgnoreCase("Paris")) {
            jComboBoxArrondissements.setSelectedIndex(0);
        } else {
            jComboBoxArrondissements.setSelectedItem("Aucun arrondissement");
        }
    }//GEN-LAST:event_jComboBoxVillesActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonNouvelleSalle;
    private javax.swing.JButton jButtonSupprimerSalle;
    private javax.swing.JButton jButtonValiderNouveauCinema;
    private javax.swing.JCheckBox jCheckBoxAccesPersonnesHandicapees;
    private javax.swing.JComboBox jComboBoxArrondissements;
    private javax.swing.JComboBox jComboBoxVilles;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabelMessage;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTableSalles;
    private javax.swing.JTextField jTextFieldAdresseCinema;
    private javax.swing.JTextField jTextFieldCodeCinema;
    private javax.swing.JTextField jTextFieldNomCinema;
    // End of variables declaration//GEN-END:variables
}
